﻿/**
 * Created by 1257D on 2016-03-23. 
 */
define(
    ["app/core/base",
        "app/core/util",
        "../echartsMeta",
        "jquery",
        "underscore",
        'JSONParse',
        'loglevel',
        "echarts"
    ],
    function (Chart, Util, Meta, $, _, JSON, log, ec) {

        var property = {
            name: '通用属性',
            config: "property",
            option: []
                .concat($.extend(true, [], Meta.titleProperties))
                .concat($.extend(true, [], Meta.legendProperties))
                .concat($.extend(true, [], Meta.tooltipProperties))
                .concat($.extend(true, [], Meta.toolboxProperties))
                .concat([
                    {
                        group: '序列',
                        id: 'f53a0a43-6d1b-43e0-b514-122a8b155ece',
                        name: '序列',
                        type: 'group',
                        items: [],
                        option: [
                            {
                                id: '8d613598-8e08-49ce-908e-7524c305910f',
                                name: '序列名称',
                                enable: true,
                                type: 'text',
                                value: '',
                                link: 'name',
                                tooltip: '序列名称，用于legend'
                            },
                            {
                                id: '17994381-e1fe-4551-a852-a5a0571ed899',
                                name: '序列绑定',
                                enable: true,
                                type: 'seriesBinding',
                                dataset: '',
                                dimension: '',
                                measure: '',
                                tooltip: '序列绑定设置，与数据集关系'
                            },
                            {
                                id: 'a320684c-8ca5-49f0-aab7-853e0fde9e5c',
                                name: '过滤列名称',
                                enable: false,
                                type: 'text',
                                value: '',
                                default: '',
                                tooltip: '绑定数据集，客户端过滤字段列名称'
                            },
                            {
                                id: '96f30ae6-6fe0-4faa-8b7f-a302a49a0434',
                                name: '过滤列默认值',
                                enable: false,
                                type: 'text',
                                value: '',
                                default: '',
                                tooltip: '绑定数据集，客户端过滤字段默认值'
                            },
                            {
                                id: 'gauge_position',
                                name: '位置',
                                enable: false,
                                type: 'text',
                                value: '50%,50%',
                                link: function (option) {
                                    var _this = this;
                                    var radius = ['0%', '50%']
                                    if (_this.enable) {
                                        var radiusArr = _this.value.split(',');

                                        if (radiusArr.length >= 2) {
                                            radius = $.parseJSON('["' + radiusArr[0] + '","' + radiusArr[1] + '"]');
                                        }
                                    }
                                    Util.setOption("center", radius, option);
                                },
                                tooltip: '仪表盘在画布中的位置'
                            },
                            {
                                id: 'gauge_size',
                                name: '表盘大小',
                                enable: false,
                                type: 'text',
                                value: "100%",
                                link: 'radius',
                                tooltip: '仪表盘大小'
                            },
                            {
                                id: 'gauge_min',
                                name: '最小值',
                                enable: true,
                                type: 'textBinding',
                                dataset: '',
                                column: {},
                                tooltip: '仪表盘刻度最小值'
                            },
                            {
                                id: 'gauge_max',
                                name: '最大值',
                                enable: true,
                                type: 'textBinding',
                                dataset: '',
                                column: {},
                                tooltip: '仪表盘刻度最大值'
                            },
                            {
                                id: 'gauge_split',
                                name: '表盘格拆分数',
                                enable: false,
                                type: 'number',
                                value: 10,
                                link: 'splitNumber',
                                tooltip: '仪表盘主刻度格个数'
                            },
                            {
                                id: 'gauge_Angle_S',
                                name: '表盘格起始角度',
                                enable: false,
                                type: 'number',
                                value: 225,
                                link: 'startAngle',
                                tooltip: '仪表盘初始值起始角度'
                            },
                            {
                                id: 'gauge_Angle_E',
                                name: '表盘格结束角度',
                                enable: false,
                                type: 'number',
                                value: -45,
                                link: 'endAngle',
                                tooltip: '仪表盘结束值角度'
                            },
                            {
                                id: 'gauge_border',
                                name: '表盘边框宽度',
                                enable: false,
                                type: 'number',
                                value: 10,
                                link: 'axisLine.lineStyle.width',
                                tooltip: '仪表盘边框宽度'
                            },
                            {
                                id: 'gauge_formatter',
                                name: '数据格式',
                                enable: false,
                                type: 'text',
                                value: "%",
                                link: function (option) {
                                    var _this = this;
                                    if (_this.enable) {
                                        var str_1 = "{value}";
                                        if (_this.value != "") {
                                            str_1 = str_1 + _this.value;
                                        }
                                        Util.setOption("detail.formatter", str_1, option);

                                    }
                                },
                                tooltip: '可以在数值前后添加文字或符号'
                            },
                            {
                                id: 'gauge_lineColors',
                                name: '轴线颜色分段',
                                enable: true,
                                type: 'text',
                                value: "[[0.2,'#FE8463'], [0.8,'#9BCA63'], [1,'#FAD860']]",//'axisLine.lineStyle.color'
                                default: "[[0.2,'#FE8463'], [0.8,'#9BCA63'], [1,'#FAD860']]",
                                link: function (option) {
                                    var _this = this;
                                    var tmpArr = [[0.2, '#008463'], [0.8, '#9BCA63'], [1, '#FAD860']];
                                    if (_this.enable) {
                                        tmpArr = eval(_this.value);
                                    }
                                    Util.setOption("axisLine.lineStyle.color", tmpArr, option);

                                },
                                tooltip: '仪表盘的轴线可以被分成不同颜色的多段。每段的结束位置和颜色可以通过一个数组来表示。'
                            }
                        ],
                        link: 'series',
                        tooltip: '字段说明:<br/>分组控件，支持动态扩展，内部可增加支持的类型属性'
                    }
                ]).concat($.extend(true, [], Meta.otherProperties)),
            //需要针对组件映射属性至组件Option
            MapOption: function (option) {
                Util.linkOption(this.option, option);
            }
        };

        var gauge = Chart.extend({
            constructor: function (layout) {
                this._layout = layout;
                this._chart = null;
                this._lastdata = null;
                this._container = null;
                this._option = {
                    Binding: [],
                    Events: [],
                    Extend: $.extend(true, {}, property),
                    Option: {
                        title: {
                            text: '业务指标完成率',
                            x: 'center',
                            y: 0
                        },
                        tooltip: {
                            formatter: "{a} <br/>{b} : {c}%"
                        },
                        toolbox: {
                            feature: {
                                restore: {},
                                saveAsImage: {}
                            }
                        },
                        series: [
                            {
                                name: '业务指标',
                                type: 'gauge',
                                min: 0,
                                max: 100,
                                detail: {formatter: '{value}%'},
                                data: [{value: 95, name: '完成数'}],
                                axisLine: {
                                    lineStyle: {
                                        color: [[0.5, "#91c7ae"], [0.8, "#63869e"], [1, "#c23531"]],
                                        width: 10
                                    }
                                }
                            }
                        ]
                    }
                };
            },
            init: function (element) {
                try {
                    this._container = element;
                    this._chart = ec.init(element, null, {
                        renderer: 'canvas'
                    });
                    this._bindEvent();
                } catch (e) {
                    log.error(e);
                }
            },
            //TODO:需要重写的部分
            _bindEvent: function () {
                var _this = this;
                this._chart.on("click", function (param) {
                    if (_this._layout
                        && _this._layout.navigate
                        && _this._option.Events
                        && _this._option.Events.length > 0) {

                        var registerEvent = _.findWhere(_this._option.Events, {Event: "SeriesClick"});
                        if (registerEvent) {
                            var pageId = registerEvent.PageId;
                            var params = registerEvent.Params;
                            var args = [];
                            var dParam = _.findWhere(params, {Value: "Dimension"});
                            if (dParam && dParam.ParamName) {
                                args.push({
                                    ParamName: dParam.ParamName,
                                    ParamValue: param.name
                                });
                            }
                            var mParam = _.findWhere(params, {Value: "Measure"});
                            if (mParam && mParam.ParamName) {
                                args.push({
                                    ParamName: mParam.ParamName,
                                    ParamValue: param.value
                                });
                            }
                            var sParam = _.findWhere(params, {Value: "SeriesName"});
                            if (sParam && sParam.ParamName) {
                                args.push({
                                    ParamName: sParam.ParamName,
                                    ParamValue: param.seriesName
                                });
                            }
                            _this._layout.navigate(pageId, args);

                        }
                        param.event.event.preventDefault();
                    }
                });
                if (!this._filterDataHandle) {
                    this._filterDataHandle = function (params) {
                        _this.filterDataHandle.call(_this, params);
                    };
                }
                this._layout.removeListener("filterData", this._filterDataHandle);
                this._layout.addListener("filterData", this._filterDataHandle);
            },
            filterDataHandle: function (params) {
                var _this = this;
                var flag = false;
                var seriesItems = _.findWhere(_this._option.Extend.option, {type: 'group'});
                $.each(seriesItems.items, function (i, item) {
                    var filterColumn = _.findWhere(item.option, {name: '过滤列名称'});
                    var filterValue = _.findWhere(item.option, {name: '过滤列默认值'});

                    if (filterColumn && filterValue
                        && filterColumn.enable && filterValue.enable
                        && filterColumn.value !== "" && filterValue.value !== ""
                    ) {
                        for (var prop in params) {
                            if (!params.hasOwnProperty(prop)) continue;
                            if (filterColumn.value === prop) {
                                filterValue.value = params[prop];
                                flag = true;
                            }
                        }
                    }
                });
                if (flag && _this._lastdata) {
                    _this.setData(_this._lastdata);
                }
            },
            example: function () {
                try {
                    this._chart.setOption(this._option.Option, true);
                } catch (e) {
                    log.error(e);
                }
            },
            _readProperty: function () {
                try {
                    if (!this._option.Extend) return;
                    Util.deepMapOption(property, this._option.Extend, this._option.Option);
                } catch (e) {
                    log.error(e);
                }
            },
            //TODO:需要重写的部分
            _bindData: function (data) {
                var tables = data;
                var _this = this;

                //根据每个option自行查找，可通过id或name，这里因为只有一个group,因此通过type查找
                var seriesItems = _.findWhere(this._option.Extend.option, {type: 'group'});

                //清除工作
                if (seriesItems.items.length > 0) {
                    // this._option.Option.legend.data = [];
                }

                //绑定数据
                $.each(seriesItems.items, function (i, item) {
                    var bindProperty = _.findWhere(item.option, {type: 'seriesBinding'});
                    var minProperty = _.findWhere(item.option, {id: 'gauge_min'});
                    var maxProperty = _.findWhere(item.option, {id: 'gauge_max'});
                    if (!bindProperty) return;

                    var dataSetCode = bindProperty.dataset;
                    var dimensionCode = bindProperty.dimension.ColumnCode;
                    var measureCode = bindProperty.measure.ColumnCode;

                    var minDataSetCode = minProperty.dataset;
                    var minColCode = minProperty.column.ColumnCode;
                    var maxDataSetCode = maxProperty.dataset;
                    var maxColCode = maxProperty.column.ColumnCode;

                    var nameProperty = _.findWhere(item.option, {name: '序列名称'});
                    //var minProperty = _.findWhere(item.option, {name: '最小值'});
                    //var maxProperty = _.findWhere(item.option, {name: '最大值'});

                    if (dataSetCode && dimensionCode && measureCode) {
                        var table = tables[dataSetCode];
                        var binding = _.findWhere(_this._option.Binding, {DataSetCode: dataSetCode});
                        var dimension = _.findWhere(binding.Dimensions, {Code: dimensionCode}).Column;
                        var measure = _.findWhere(binding.Measures, {Code: measureCode}).Column;
                        var data = [];
                        table = _this._filterTable(item.option, table);
                        $.each(table, function (j, row) {
                            data.push({
                                value: row[measure],
                                name: row[dimension]
                            });
                        });


                        if (_this._option.Option.series.length >= i + 1) {
                            _this._option.Option.series[i].type = 'gauge';
                            _this._option.Option.series[i].name = nameProperty.value;
                            _this._option.Option.series[i].min = table[0][minColCode];
                            _this._option.Option.series[i].max = table[0][maxColCode];
                            _this._option.Option.series[i].data = data;

                        } else {
                            _this._option.Option.series.push({
                                name: nameProperty.value,
                                type: 'gauge',
                                selectedMode: 'single',
                                data: data
                            })
                        }

                    }
                });
            },
            _filterTable: function (option, table) {
                var filterColumn = _.findWhere(option, {name: '过滤列名称'});
                var filterValue = _.findWhere(option, {name: '过滤列默认值'});

                if (filterColumn && filterValue
                    && filterColumn.enable && filterValue.enable
                    && filterColumn.value !== "" && filterValue.value !== ""
                ) {
                    var tableCopy = _.map(table, _.clone);
                    return _.filter(tableCopy, function (row) {
                        return row[filterColumn.value] === filterValue.value;
                    });
                }
                return table;
            },
            setData: function (data) {
                try {
                    this._readProperty();

                    if (data
                        && this._option.Binding
                        && this._option.Binding.length > 0
                        && this._option.Extend) {

                        this._bindData(data);

                        this._readProperty();
                    }
                    this._chart.setOption(this._option.Option, true);

                    //Util.setEChartsMeta(this, this._container, this._option.Extend.option);
                } catch (e) {
                    log.error(e);
                }
            },
            setOption: function (option) {
                try {
                    return this._option = $.extend(true, {}, option);
                } catch (e) {
                    log.error(e);
                }
            },
            getOption: function () {
                try {
                    this._readProperty();
                } catch (e) {
                    log.error(e);
                }
                return this._option;
            },
            setTheme: function (theme) {
                try {
                    this._chart.setTheme(theme);
                } catch (e) {
                    log.error(e);
                }
            },
            resize: function () {
                try {
                    this._chart.resize();
                } catch (e) {
                    log.error(e);
                }
            },
            showLoading: function () {
                try {
                    if (this._layout && this._layout.showLoading) {
                        this._layout.showLoading(this);
                    }
                } catch (e) {
                    log.error(e);
                }
            },
            hideLoading: function () {
                try {
                    if (this._layout && this._layout.hideLoading) {
                        this._layout.hideLoading(this);
                    }
                } catch (e) {
                    log.error(e);
                }
            },
            dispose: function () {
                try {
                    this._chart.dispose();
                    this._layout.removeListener("filterData", this._filterDataHandle);
                } catch (e) {
                    log.error(e);
                }
            },
            getElement: function () {
                return this._container;
            },
            getChart: function () {
                return this._chart;
            }
        });

        return {
            Chart: gauge,
            Property: property
        };
    });
